
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.Sections;

public class GenericSectionsDAO extends AutoKeys implements org.jetnuke.dao.SectionsDAO {

	/* (non-Javadoc)
	 * @see org.jetnuke.model.SectionsModel#retrieveByPK(int)
	 */
	public Sections retrieveByPK(int id) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("SectionModel.selectByID"));
		p.setInt(1, id);
		
		ResultSet rs = p.executeQuery();
		Sections s = new Sections();
		
		if (rs.next()) {
			fillSectionsFromResultSet(s, rs);
		}
		
		rs.close();
		p.close();

		return s;
	}

	/**
	 * @param s
	 * @param rs
	 */
	protected void fillSectionsFromResultSet(Sections s, ResultSet rs)throws Exception {
		s.setIMAGE(rs.getString("IMAGE"));
		s.setSECID(rs.getInt("SECID"));
		s.setSECNAME(rs.getString("SECNAME"));
		
	}

	protected List processSelectAll(ResultSet rs)throws Exception {
		List list = new ArrayList();
		while (rs.next()) {
			Sections u = new Sections();
			fillSectionsFromResultSet(u,rs);			
			list.add(u);
		}
		
		return list;
	}
	public List selectAll() throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("SectionModel.selectAll"));
			
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.SectionsModel#addNew(org.jetnuke.entities.Sections)
	 */
	public int addNew(Sections sec) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("SectionModel.addNew");
		this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("SectionsModel.lastGeneratedSectionID"));
		initNewSection(sec, p);
		
		int id = this.executeAutoKeysQuery(p);
		p.close();		
		return id;	}

	/**
	 * @param sec
	 * @param p
	 */
	private void initNewSection(Sections sec, PreparedStatement p) throws Exception{
		p.setString(1,sec.getIMAGE());
		p.setString(2,sec.getSECNAME());
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.SectionsModel#update(org.jetnuke.entities.Sections)
	 */
	public void update(Sections sc) throws Exception {
		PreparedStatement p = JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("SectionModel.update"));
		p.setString(1,sc.getIMAGE());
		p.setString(2,sc.getSECNAME());
		p.setInt(3,sc.getSECID());
		p.executeUpdate();
		p.close();
		
	}

}
